Sorting and Searching


Quick Sort (qsort and qsort_s)

It is possible to sort the elements of an array as it is shown in the following code.
Es posible ordenar los elementos de un arreglo como se muestra en el código siguiente.

Program.h
#pragma once //______________________________________ Program.h
#include "resource.h"

class Program: public Win::Dialog
{
public:
     Program()
     {

     }
     ~Program()
     {
     }
     static int LessThan(void * data, const void * value1, const void * value2);
     . . .
};


Program.cpp
. . .
void Program::Window_Open(Win::Event& e)
{
     int number[6];
     number[0] = 5;
     number[1] = 2;
     number[2] = 0;
     number[3] = 1;
     number[4] = 4;
     number[5] = 3;
     qsort_s(number, 6, sizeof(int), LessThan, NULL);
}

int Program::LessThan(void * data, const void * value1, const void * value2)
{
     if (*((int*)value1) == *((int*)value2)) return 0;
     return *((int*)value1) < *((int*)value2) ? -1 : 1;
}


Sorting using the STL

The following example shows how to sort a vector using a custom sort function.
El siguiente ejemplo muestra cómo ordenar un vector usando una función personalizada para ordenar.

Program.h
#pragma once //______________________________________ Program.h
#include "resource.h"

class Program: public Win::Dialog
{
public:
     Program()
     {

     }
     ~Program()
     {
     }
     static bool LessThan(int value1, int value2);
     . . .
};


Program.cpp
. . .

void Program::Window_Open(Win::Event& e)
{
     vector<int> number;
     number.resize(6);
     number[0] = 5;
     number[1] = 2;
     number[2] = 0;
     number[3] = 1;
     number[4] = 4;
     number[5] = 3;
     std::sort(number.begin(), number.end(), LessThan);
}

bool Program::LessThan(int value1, int value2)
{
     return value1 < value2;
}


Binary Search (bsearch and bsearch_s)

It is possible to find a specific element in a sorted array as it is shown in the following code.
Es posible encontrar un elemento específico en un arreglo ordenado como se muestra en el siguiente código.

Program.cpp
. . .
void Program::Window_Open(Win::Event& e)
{
     int number[6];
     number[0] = 5;
     number[1] = 2;
     number[2] = 0;
     number[3] = 1;
     number[4] = 4;
     number[5] = 3;

     //______________________________________________ Quick Sort
     qsort_s(number, 6, sizeof(int), LessThan, NULL);
     //______________________________________________ Binary Search
     int numberToFind = 5;
     int* result = (int*)bsearch_s(&numberToFind, number, 6, sizeof(int), LessThan, NULL);
     if (result == NULL)
     {
          // Not found
     }
     else
     {
          // Found
     }
}

int Program::LessThan(void * data, const void * value1, const void * value2)
{
     if (*((int*)value1) == *((int*)value2)) return 0;
     return *((int*)value1) < *((int*)value2) ? -1 : 1;
}

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home